<template>
  <div style="width: 100%;padding: 10px">
    <el-card class="box-card">
      <div>
        <div style="display: flex;align-items: center;justify-content: space-between">
          <div class="details_Header">
            <div class="deleted_Line"/>
            <span class="details_HeaderTitle">订单信息</span>
          </div>
          <div style="display: flex">
            <el-button   v-if="form.askfor != null && form.askfor.status==0" @click="askforConfirmClick" v-permission="['askfor.confirm']">同意退款
            </el-button>
            <el-button   v-if="form.askfor != null && form.askfor.status==0 " @click="cancelAskfor" v-permission="['askfor.cancel']">拒绝退款
            </el-button>
            <el-button   v-if="form.askfor != null && form.askfor.status!=0  " @click="refundsAskfor" v-permission="['askfor.refund']">确认退款
            </el-button>
            <el-button   v-permission="['saleout.add']" v-show="shippingStatus ==0 && paymentStatus == 1"  type="primary"
                       @click="sendClick">接单
            </el-button>
            <el-button  v-permission="['order.complete']" v-show="shippingStatus ==1 && paymentStatus == 1" type="primary"
                      @click=complete>完成
            </el-button>
            <el-button   v-permission="['order.return']" v-show="shippingStatus ==1 && paymentStatus == 1"  type="primary"
                       @click="returnsClick">退货
            </el-button>
            <el-button   v-permission="['order.add']"  v-show="shippingStatus ==0 && paymentStatus == 1" type="primary"
                       @click="cancelClick">关闭订单
            </el-button>
            <el-button
             v-permission="['order.del']"
              v-show="(orderStatus == 0 && paymentStatus == 0) || orderStatus == 3 "
              type="primary"
              style="margin-left: 10px"
              @click="delClick"
            >删除订单
            </el-button>
            <el-button v-show="orderStatus > 0  " v-permission="['order.print']" type="primary" @click="printClick">打印
            </el-button>
            <el-button v-show="orderStatus > 0 " v-permission="['order.print']" type="primary" @click="exportViewClick">
              导出
            </el-button>
          </div>
        </div>
        <div class="deleted_OrderHeader" style="border-left: none;">
          <el-row :gutter="24">
            <el-col :span="8">
              <span class="deleted_Row_Headings">订单编号：</span>
              <span class="deleted_OrderTitle">{{ form.sn }}</span>
            </el-col>
            <el-col :span="8"/>
            <el-col :span="8">
              <span class="deleted_Row_Headings">订单状态：</span>
              <span class="deleted_OrderTitle" style="color: rgb(64, 158, 255)">{{ form.statusDescr }}</span>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="8">
              <span class="deleted_Row_Headings">销售日期：</span>
              <span class="deleted_OrderTitle">{{ form.orderDate | dateFormatter }}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">开票类型：</span>
              <span class="deleted_OrderTitle">{{ form.taxType | watchTaxType }}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">所属部门：</span>
              <span class="deleted_OrderTitle">{{ officeName }}</span>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="8">
              <span class="deleted_Row_Headings">订货方式：</span>
              <span class="deleted_OrderTitle">{{ form.orderMethod | watchOrderMatch }}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">配送方式：</span>
              <span class="deleted_OrderTitle">{{ form.shippingMethod | watchShippingMethod }}</span>
            </el-col>
            <el-col :span="8">
              <span class="deleted_Row_Headings">销售人员：</span>
              <span class="deleted_OrderTitle">{{ operatorName }}</span>
            </el-col>
          </el-row>
        </div>
        <div class="details_PayHeader">
          <div class="deleted_Line"/>
          <span class="details_HeaderTitle">买家信息</span>
        </div>
        <div>
          <el-row :gutter="24" class="deleted_OrderContent" v-show="form.orderType == 0">
            <el-col :span="24">
              <div class="details_Buyers">
                <span class="deleted_Row_Headings deleted_Row_leftTitle">取餐号：</span>
                <span class="deleted_OrderName">{{ form.num }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <div class="details_Buyers">
                <span class="deleted_Row_Headings deleted_Row_leftTitle">客户名称：</span>
                <span class="deleted_OrderName">{{ memberName }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent" v-show="form.orderType == 1">
            <el-col :span="24">
              <div class="details_Buyers">
                <span class="deleted_Row_Headings deleted_Row_leftTitle">主厨：</span>
                <span class="deleted_OrderName">{{ sendForm.chefName }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <div class="details_Buyers">
                <span class="deleted_Row_Headings deleted_Row_leftTitle">{{form.orderType==0?'预计送达：':'预定时间：'}}</span>
                <span class="deleted_OrderName">{{ form.estimateDate | datetimeFormatter}}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent" v-show="form.orderType == 1">
            <el-col :span="24">
              <div class="details_Buyers">
                <span class="deleted_Row_Headings deleted_Row_leftTitle">可否调配：</span>
                <span class="deleted_OrderName">{{ form.allocateChef == true?'可以调配':'不能调配' }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <div class="details_Buyers">
                <span class="deleted_Row_Headings deleted_Row_leftTitle">{{form.orderType == 1 ?'预定地址':'收货信息'}}：</span>
                <div>
                  <span class="deleted_OrderName">{{ form.consignee }} {{ form.phone }}</span>
                  <span class="deleted_OrderName" style="margin-top: 5px; width: auto;">{{ form.address }}</span>
                </div>
                <!--                <el-button style="margin-left: 20px" type="primary" @click="addressClick" v-show="weekType == true && orderStatus == 1 && shippingStatus ==0">修改地址</el-button>-->
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="8">
              <span class="deleted_Row_Headings deleted_Row_leftTitle">买家留言：</span>
              <span class="deleted_OrderTitle">{{ form.memo }}</span>
            </el-col>
          </el-row>
        </div>
        <div class="product_header_name">
          <div class="deleted_Line"/>
          <span style="margin: 10px 5px;">商品明细</span>
        </div>
        <!--商品规格-->
        <el-table
          :data="form.itemList"
          border
          show-summary
          stripe
          style="width: 100%"
        >
          <el-table-column
            label="排序"
            type="index"
            width="50"
            align="center"
            fixed
          />
          <el-table-column
            label="缩略图"
            width="80"
          >
            <template slot-scope="{row}">
              <img :src="row.thumbnail" style="width: 100%;"></img>
            </template>
          </el-table-column>
          <el-table-column
            label="商品名"
          >
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{ row.spec }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="170"
          >
            <template slot-scope="{row}">
              <span>{{ row.sn }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            width="50"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{ row.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            align="right"
            width="50"
          />
          <el-table-column
            label="发货"
            prop="shippedQuantity"
            align="right"
            width="50"
          />
          <el-table-column
            label="退货"
            prop="returnQuantity"
            align="right"
            width="50"
          />
          <el-table-column
            label="单价"
            align="right"
            width="70"
          >
            <template slot-scope="{row}">
              <span>{{ row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            width="70"
            align="right"
            prop="amount"
          />
          <el-table-column
            label="优惠"
            width="70"
            align="right"
            prop="discount"
          />
          <el-table-column
            label="实收"
            width="70"
            align="right"
            prop="subTotal"
          />
        </el-table>
        <el-row class="deleted_OrderHeader" style="padding-left:30px">
          <el-col :span="3">
            <span class="deleted_Row_Headings">运费：</span>
            <span class="deleted_OrderTitle">+{{ form.freight }}</span>
          </el-col>
               <el-col :span="3">
            <span class="deleted_Row_Headings">包装费：</span>
            <span class="deleted_OrderTitle">+{{form.packagingFee}}</span>
          </el-col>
                 <el-col :span="3">
            <span class="deleted_Row_Headings">平台优惠：</span>
            <span class="deleted_OrderTitle">-{{form.couponDiscount}}</span>
          </el-col>
                 <el-col :span="3">
            <span class="deleted_Row_Headings">店铺优惠：</span>
            <span class="deleted_OrderTitle">-{{form.discount}}</span>
          </el-col>
          <el-col :span="3">
            <span class="deleted_Row_Headings">预计收入：</span>
            <span class="deleted_OrderTitle" style="color:red">{{form.distributionAmount}}</span>
          </el-col>
          <el-col :span="5">
            <span class="deleted_Row_Headings">顾客实际付款：</span>
            <span class="deleted_OrderTitle" style="color:red">{{ form.amountPayable }}</span>
          </el-col>
        </el-row>
        <div class="product_header_Plans" v-show="orderPlans.length > 0">
          <div class="product_header_Plans_left">
            <div class="deleted_Line"/>
            <span style="margin: 10px 5px;">套餐配送</span>
          </div>
          <div style="display: flex">
            <el-button type="primary" @click="changeTime">修改送货时间</el-button>
            <el-button type="primary" @click="addressClick">修改送货地址</el-button>
            <el-button type="primary" @click="recoveryClick">恢复报停</el-button>
            <el-button type="primary" @click="dialogVisible = true">报停</el-button>
          </div>

        </div>
        <el-table
          :data="orderPlans"
          border
          stripe
          style="width: 100%"
          v-show="orderPlans.length > 0"
        >
          <el-table-column
            label="排序"
            type="index"
            width="50"
            align="center"
            fixed
          />
          <el-table-column
            label="缩略图"
            width="80"
          >
            <template slot-scope="{row}">
              <img :src="row.thumbnail" style="width: 100%;"></img>
            </template>
          </el-table-column>
          <el-table-column
            label="商品名"
            width="200"
          >
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            align="center"
            width="200"
          >
            <template slot-scope="{row}">
              <span>{{ row.spec }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="菜单"
          >
            <template slot-scope="{row}">
              <div style="display: flex;flex-direction: column">
                 <span v-for="item in row.itemList">{{item.productName}}*{{item.convRate}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            width="100"
          >
            <template slot-scope="{row}">
              <span>{{ row.status | planStatus}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="次数"
            align="center"
            width="80"
          >
            <template slot-scope="{row}">
              <span>{{ row.seqno }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="配送日期"
            align="center"
            width="150"
          >
            <template slot-scope="{row}">
              <span>{{ row.planDate | dateFormatter}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            align="center"
            width="80"
          >
            <template slot-scope="{row}">
              <span>{{ row.unit }}</span>
            </template>
          </el-table-column>
        </el-table>


        <div class="product_header_name" v-show="form.orderType == 1">
          <div class="deleted_Line"/>
          <span style="margin: 10px 5px;">菜品清单</span>
        </div>
        <div v-for="item in detailedList" v-show="form.orderType == 1">
          <div class="deleted_OrderHeader">
            <el-row :gutter="24">
              <el-col :span="6">
                <span style="padding-left: 20px;">名称 :</span>
                <span>{{ item.name }}</span>
              </el-col>
              <el-col :span="3">
                <span>数量 :</span>
                <span>{{ item.params }}</span>
              </el-col>
              <el-col :span="15">
                <span>用料 : </span>
                <span>{{ item.memo }}</span>
              </el-col>
            </el-row>
          </div>
        </div>

        <div class="product_header_name">
          <div class="deleted_Line"/>
          <span style="margin: 10px 5px;">付款方式</span>
        </div>
        <div v-for="item in payments">
          <div class="deleted_OrderHeader">
            <el-row :gutter="24">
              <el-col :span="1">
                <span style="padding-left: 20px;">├</span>
              </el-col>
              <el-col :span="4">
                <span>{{ item.createDate | datetimeFormatter }}</span>
              </el-col>
              <el-col :span="4">
                <span>付款方式 :</span>
                <span>{{ item.paymentPluginName }}</span>
                <span style="margin-left:10px" class="submit_payMethod_Content_Date" v-if="item.attach.quantity !=undefined && (item.paymentPluginId == 'waterTicketPayPlugin' || item.paymentPluginId == 'couponCodePayPlugin')">(抵扣{{item.attach.quantity}}张)</span>
              </el-col>
              <el-col :span="3">
                <span>付款金额 :</span>
                <span>{{ item.amount }}</span>
              </el-col>
              <el-col :span="3">
                <span style="color: rgb(64, 158, 255)">{{ item.status | watchPayment }}</span>
              </el-col>
              <el-col :span="9">
                <span>备注 : </span>
                <span>{{ item.memo }}</span>
              </el-col>
            </el-row>
          </div>
        </div>

        <div class="product_header_name">
          <div class="deleted_Line"/>
          <span style="margin: 10px 5px;">订单日志</span>
        </div>
        <div v-for="item in orderLog">
          <div class="deleted_OrderHeader">
            <el-row :gutter="20">
              <el-col :span="1">
                <span style="padding-left: 20px;">├</span>
              </el-col>
              <el-col :span="4">
                <span>{{ item.createDate | datetimeFormatter }}</span>
              </el-col>
              <el-col :span="19">
                <span>{{ item.content }}</span>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 发货 -->
    <el-dialog
      v-el-drag-dialog
      title="接单"
      :visible.sync="sendType"
      width="45%"
      append-to-body
      :before-close="sendClose"
    >
      <div style="position: relative;">
        <sendList ref="send" :memberMemo="memberMemo" :key="times" :bomType="bomType" :weekType="weekType" :sendForm="sendForm"
                  @sendClose="sendClose" @findClick="findClick" />
        <div style="display: flex;justify-content: flex-end;align-items: center;margin-top: 20px">
          <el-button  type="primary" :loading="clicked" @click="delivery">发货</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      v-el-drag-dialog
      title="退货"
      :visible.sync="returnsType"
      width="40%"
      append-to-body
      :before-close="returnsClose"
    >
      <div style="position: relative; ">
        <returnsList
          ref="returns"
          :key="times"
          :returns-form="sendForm"
          @returnsClose="returnsClose"
          @findClick="findClick"
        />
        <div style="display: flex;justify-content: flex-end;align-items: center;margin-top: 20px">
          <el-button type="primary" :loading="returnClick" @click="returnGoods">确认退货</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="物流信息" width="60%" :visible.sync="logisticsVisible">
      <div class="el-dialog-div">
        <el-table :data="logisticsData" border>
          <el-table-column label="物流单号" width="140">
            <template slot-scope="scope">{{ scope.row.trackingNo || '暂未送货' }}</template>
          </el-table-column>
          <el-table-column label="商品图片" width="80">
            <template slot-scope="scope">
              <img :src="scope.row.thumbnail" style="width: 100%; height: 100%;">
            </template>
          </el-table-column>
          <el-table-column label="商品名称">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.name" placement="top">
                <span>{{ scope.row.name }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="商品规格">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.spec" placement="top">
                <span>{{ scope.row.spec }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="80">
            <template slot-scope="scope">
              <el-link type="primary" @click="logisticDetail(scope.row.trackingNo)">{{ scope.row.trackingNo? '查看物流': ''
                }}
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <el-dialog title="物流查询" width="60%" :visible.sync="logisticsDetailVisible">
      <div class="el-dialog-div">
        <el-table :data="logisticsDetailData">
          <el-table-column prop="ftime" label="时间" width="170"/>
          <el-table-column label="物流查询">
            <template slot-scope="scope">
              <span :style="{'color': scope.$index===0? '#409EFF': ''}">{{ scope.row.context }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!--    套餐报停-->
    <el-dialog
      title="套餐报停"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <div style="width: 100%;display: flex;justify-content: center;align-items: center">
        <el-date-picker
          v-model="pauseDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="pauseClick">确 定</el-button>
  </span>
    </el-dialog>
    <!--    地址修改-->
    <el-dialog
      title="地址修改（点击选择地址）"
      :visible.sync="addressType"
      width="70%"
      :before-close="addressClose">
      <el-table
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%">
        <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            property="consignee"
            label="姓名"
            width="120">
          </el-table-column>
          <el-table-column
            property="phone"
            label="电话"
            width="120">
        </el-table-column>
        <el-table-column
          property="address"
          label="详细地址">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addressType = false">取 消</el-button>
        <el-button type="primary" @click="chooseClick">确 定</el-button>
        <el-button type="primary" @click="addressAdd">新增地址</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="打印安装教程"
      :visible.sync="isNoInstall"
      width="600px"
      v-el-drag-dialog
      append-to-body
      :before-close="installClose">
      <div style="position: relative;height: 30vh;overflow: auto">
          <div>
              <span style="font-weight: bold">未检测到您的打印控件，请检查是否安装以下两个打印控件</span>
              <span style="display: block;margin-left: 20px;line-height: 20px">1、install_lodop64.exe（或者32位，根据自己的电脑位数）</span>
              <span style="display: block;margin-left: 20px;line-height: 20px">2、CLodopPrint_Setup_for_Win32NT.exe（32位64位皆可用）</span>
              <span style="font-weight: bold">已经下载</span>
              <span style="display: block;margin-left: 20px;line-height: 20px">如果已有两个软件，请检查是否已经打开服务。</span>
            <span style="font-weight: bold">未下载</span>
              <span style="display: block;margin-left: 20px;line-height: 20px">如果没有两个控件的客户，您可以点击下面的下载地址自行前往下载<a style="color: #00B6FB;margin-left: 20px" target="view_window" href="http://www.c-lodop.com/download.html">下载地址</a></span>
              <span style="display: block;margin-left: 20px;line-height: 20px">(提示：请下载Lodop发型包Windows版，里面包含所需的两个控件，安装完后请刷新本页面方可使用打印，install_lodop64.exe软件下载完打开即可，
                CLodopPrint_Setup_for_Win32NT.exe需要安装，您可以直接选择开机自动启动)</span>
          </div>
      </div>
    </el-dialog>
    <el-dialog
      title="新增地址"
      :visible.sync="receiverVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="receiverClose">
      <div style="position: relative;height: 60vh;overflow: auto">
        <receiverAdd @orderReceiver="orderReceiver" pathType="0" :memberId="form.memberId"></receiverAdd>
      </div>
    </el-dialog>
    <el-dialog
      title="修改配送时间"
      :visible.sync="timeVisible"
      width="650px"
      v-el-drag-dialog
      append-to-body
      :before-close="timeClose">
        <div>
            <div style="display: flex; flex-direction: column;">
              <el-select v-model="weekDate" multiple placeholder="请选择" @change="weekClick">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div style="margin-top: 20px">
              <span>预计送达时间：{{date | dateFormatter}}</span>
            </div>
          <div style="display: flex;justify-content: flex-end">
            <el-button @click="cancelTime">取 消</el-button>
            <el-button type="primary" @click="timeClick">确 定</el-button>
          </div>
        </div>
    </el-dialog>
    <orderPrint @isTeach="isTeach" v-if="isPrintShow==true" :form="form" :isShipping="isShipping"
                :signName="signName" :memoName="memoName"     :title="title" style="display: none" :sendForm="sendForm" ref="orderPrint"></orderPrint>
  </div>
</template>

<script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import orderPrint from "@/components/OrderPrint/orderPrint";
import { EventBus } from "@/api/eventBus";
import {
  update,
  calculate,
  find,
  cancel,
  confirm,
  send,
  refunds,
  returns,
  del,
  print,
  exportView,
  pause,
  calculateEstimateDate,
  updateWeekAndReceiver,
  complete,
} from "@/api/order";
import { update as memberupdate } from "@/api/member";
import { trackingNo_query, delivery_query } from "@/api/shipping";
import utils from "../../utils/utils.js";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import sendList from "./components/send";
import returnsList from "./components/returns";
import { mapGetters } from "vuex";
import { list as addressList } from "@/api/receiver";
import receiverAdd from "@/views/receiver/add";
import printJs from "print-js";
import {find as productFind} from "@/api/product"
import { confirm as askforConfirm ,cancel as askforCancel,refunds as askforRefunds} from '../../api/askfor'
export default {
  naem: "order-view",
  directives: { elDragDialog, permission },
  data() {
    return {
      sendForm: {},
      bomType: "",
      clicked: false,
      isPrintShow: false,
      deliveryClick: false,
      returnClick: false,
      memoName: "买家",
      signName: "客户",
      week: [],
      weekDate: [],
      form: {
        id: "",
      },
      weekTime: "",
      timeVisible: false,
      times: null,
      pageNum: 1,
      options: [
        {
          value: "1",
          label: "周一",
        },
        {
          value: "2",
          label: "周二",
        },
        {
          value: "3",
          label: "周三",
        },
        {
          value: "4",
          label: "周四",
        },
        {
          value: "5",
          label: "周五",
        },
        {
          value: "6",
          label: "周六",
        },
        {
          value: "7",
          label: "周七",
        },
      ],
      pageSize: 20,
      isNoInstall: false,
      isShipping: true,
      logisticsData: [], // 物流信息
      logisticsDetailData: [], // 物流详情
      orderLog: [],
      memberName: "",
      officeName: "",
      title: "销售",
      date: "",
      operatorName: "",
      sendType: false,
      orderStatus: 0,
      paymentStatus: 0,
      shippingStatus: 0,
      returnsType: false,
      logisticsVisible: false,
      logisticsDetailVisible: false,
      payments: [],
      pdfUrl: "",
      memberMemo: "",
      weekType: false,
      orderPlans: [],
      dialogVisible: false,
      addressType: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pauseDate: "",
      tableData: [],
      currentRow: null,
      receiverId: "",
      receiverVisible: false,
      detailedList:[]
    };
  },
  watch: {
    // 只要路由发生变化就重新获取数据
    $route(newVal, oldVal) {
      console.log(newVal);
      if (newVal.name == "order-view" && newVal.query.id != this.form.id) {
        this.form.id = newVal.query.id;
        this.findClick();
      }
    },
  },
  computed: {
    ...mapGetters(["token"]),
  },
  filters: {
    watchStatus(val) {
      if (val == 0) {
        return "待付款";
      } else if (val == 1) {
        return "已付款";
      } else if (val == 2) {
        return "待退款";
      } else if (val == 3) {
        return "已退款";
      }
    },
    watchOrderMatch(val) {
      if (val == 0) {
        return "线上订单";
      } else if (val == 1) {
        return "人工报单";
      } else if (val == 2) {
        return "门店自提";
      }
    },
    watchShippingMethod(val) {
      if (val == 0) {
        return "普通快递";
      } else if (val == 1) {
        return "到店提货";
      } else if (val == 2) {
        return "同城配送";
      }
    },
    //       watchShippingMethod(val){

    //        if (val == 0) {
    //           return '到店自提'
    //         } else if (val == 1) {
    //           return '店家配送'
    //         } else if (val == 2) {
    //           return '骑手配送'
    //         }
    // },
    watchTaxType(val) {
      if (val == 0) {
        return "不开票";
      } else if (val == 1) {
        return "增票";
      } else if (val == 2) {
        return "普票";
      }
    },
    watchPayment(val) {
      if (val == 0) {
        return "等待支付";
      } else if (val == 1) {
        return "支付成功";
      } else if (val == 2) {
        return "超时关闭";
      } else if (val == 3) {
        return "付款失败";
      }
    },
    watchNum(val) {
      if (val == undefined) {
        return 0;
      } else {
        return val;
      }
    },
    planStatus(val) {
      if (val == "0") {
        return "待配送";
      } else if (val == "1") {
        return "配送中";
      } else if (val == "2") {
        return "配送完成";
      }
    },
  },
  created() {
    var _this = this;
    this.times = new Date().getSeconds();
    _this.form.id = this.$route.query.id;
    let date = new Date();
    _this.findClick();
    EventBus.$on("order-edit", (res) => {
      // 监听新增完毕
      // 更新列表数组
      console.log(res);
      _this.form.id = res.id;
      _this.findClick();
    });
    EventBus.$on("order-view", (res) => {
      // 监听新增完毕
      // 更新列表数组
      console.log(res);
      _this.form.id = res.id;
      _this.findClick();
    });
    this.calculateEstimateDateClick();
  },
  components: { sendList, returnsList, receiverAdd, orderPrint },
  methods: {
    complete() {
      const params = new URLSearchParams();
      params.append("id", this.form.id);
        this.$confirm("确定完成?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(()=>{
          complete(params)
        .then((response) => {
          this.findClick();
          this.$router.push({
            path: "/order/list",
          });
        })
        .catch((error) => {
          console.log(err);
        });
      })

    },
    weekClick(data) {
      this.weekTime = data.join("");
      this.calculateEstimateDateClick();
    },
    calculateEstimateDateClick() {
      var _this = this;
      console.log(_this.weekTime);
      const params = new URLSearchParams();
      params.append("week", _this.weekTime);
      calculateEstimateDate(params)
        .then((response) => {
          console.log(response);
          _this.date = response.data.estimateDate;
        })
        .catch((error) => {
          console.log("error!!");
        });
    },
    timeClose() {
      this.timeVisible = false;
      this.findClick();
    },
    installClose() {
      this.isNoInstall = false;
    },
    changeTime() {
      this.timeVisible = true;
    },
    cancelTime() {
      this.timeVisible = false;
      this.findClick();
    },
    timeClick() {
      if (this.weekTime == "") {
        this.$message({
          message: "请选择配送时间",
          offset: 120,
          center: true,
        });
        return;
      }
      const params = new URLSearchParams();
      params.append("orderId", this.form.id);
      params.append("weekTime", this.weekTime);
      updateWeekAndReceiver(params)
        .then((res) => {
          console.log(res);
          this.$message({
            message: "修改成功",
            offset: 120,
            center: true,
          });
          this.timeVisible = false;
          this.findClick();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    recoveryClick() {
      var _this = this;
      this.$confirm("确定恢复?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const params = new URLSearchParams();
        params.append("orderId", this.form.id);
        pause(params)
          .then((res) => {
            console.log(res);
            _this.$message({
              message: "恢复报停成功",
              offset: 120,
              center: true,
            });
            this.dialogVisible = false;
            _this.findClick();
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    findClick() {
      var _this = this;
      var form = {};
      find(this.form.id)
        .then((response) => {
          if (response.data.order.orderType == 1){
            _this.productFindClick(response.data.order.itemList[0].productId)
          }
          console.log(response);
          form = response.data;
          this.sendForm = form;
          console.log(this.sendForm);
          _this.orderLog = response.data.orderLog.sort((now, next) => next.createDate - now.createDate);
          // debugger
          _this.form = response.data.order;
          response.data.payments.forEach((item) => {
            if (item.attach != "") {
              item.attach = JSON.parse(item.attach);
            }
          });
          _this.payments = response.data.payments;
          _this.memberName = response.data.memberName;
          _this.operatorName = response.data.operatorName;
          _this.officeName = response.data.officeName;
          _this.paymentStatus = response.data.order.paymentStatus;
          _this.orderStatus = response.data.order.orderStatus;
          _this.shippingStatus = response.data.order.shippingStatus;
          _this.bomType = response.data.bomType;
          _this.weekDate = _this.sendForm.order.weekTime.split("");
          this.weekTime = this.sendForm.order.weekTime;
          _this.memberMemo = response.data.memberMemo;
          _this.orderPlans = response.data.orderPlans;
          if (!utils.isNull(response.data.order.itemList)) {
            var packageForm = [];
            response.data.order.itemList.forEach(function (item) {
              if (item.subType == 1) {
                packageForm.push(item);
              }
            });
            if (packageForm.length > 0) {
              _this.weekType = true;
            } else {
              _this.weekType = false;
            }
          }
        })
        .catch((error) => {});
    },
    memberClick() {
      var _this = this;
      var form = {
        id: _this.form.memberId,
        memo: _this.memberMemo,
      };
      memberupdate(form)
        .then((response) => {
          this.$message({
            message: "修改成功",
            offset: 120,
            center: true,
          });
        })
        .catch((error) => {});
    },
    editClick() {
      this.$router.push({
        path: "/order/edit",
        query: { id: this.form.id },
      });
    },
    cancelClick() {
      this.$confirm("确定关闭?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        cancel(this.form.id)
          .then((response) => {
            console.log(response);
            this.$message({
              message: response.content,
              offset: 120,
              center: true,
            });
            this.findClick();
            EventBus.$emit("order-view", response.data);
          })
          .catch((error) => {});
      });
    },
    refundClick() {
      refunds(this.form.id)
        .then((response) => {
          this.$message({
            message: response.content,
            offset: 120,
            center: true,
          });
          this.findClick();
          EventBus.$emit("order-view", response.data);
        })
        .catch((error) => {});
    },
    sendClick() {
      this.sendType = true;
      this.times = new Date().getSeconds();
    },
    sendClose() {
      this.sendType = false;
    },
    returnsClick() {
      // this.returnsType = true;
      // this.times = new Date().getSeconds();
      var _this = this
      this.$confirm("确定退款?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(()=>{
        var itemList = []
        returns(_this.form.id,'', itemList).then(res => {
          console.log(res)
          _this.$message({
            message: '退货成功',
            offset: 120,
            center: true,
          });
          _this.findClick();
        }).catch(err => {
        })
      })
    },
    returnsClose() {
      this.returnsType = false;
    },
    logisticsClick() {
      // 查看物流
      const params = new URLSearchParams();
      params.append("pageNum", this.pageNum);
      params.append("pageSize", this.pageSize);
      params.append("orderId", this.form.id);
      trackingNo_query(params)
        .then((res) => {
          console.log(res);
          this.logisticsData = res.data.data;
          this.logisticsVisible = true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    logisticDetail(trackingNo) {
      this.logisticsDetailData = [];
      delivery_query({ trackingNo })
        .then((res) => {
          console.log(res);
          this.logisticsDetailData = res.data.data;
          this.logisticsVisible = false;
          this.logisticsDetailVisible = true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    delClick() {
      var _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          del(_this.form.id)
            .then((response) => {
              // EventBus.$emit('order-view', response.data)
              EventBus.$emit("order-delete", response.data);
              _this.$store
                .dispatch("tagsView/delView", _this.$route)
                .then(({ visitedViews }) => {
                  _this.$router.push({
                    path: "/order/list",
                  });
                }); // 关闭当前tab回到列表
              _this.$message({
                message: response.content,
                offset: 120,
                center: true,
              });
            })
            .catch((error) => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },
    delivery() {
      this.clicked = true;
      this.$confirm("确认发货?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        setTimeout(() => {
          this.clicked = false;
        }, 2000);
        this.$refs.send.delivery();
      });
    },
    aDeliveryClick() {
      this.deliveryClick = true;
      this.$confirm("确认发货并出库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        setTimeout(() => {
          this.deliveryClick = false;
        }, 2000);
        this.$refs.send.aDeliveryClick();
      });
    },
    returnGoods() {
      this.returnClick = true;
      this.$confirm("确认退货?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        setTimeout(() => {
          this.returnClick = false;
        }, 2000);
        this.$refs.returns.returnsClick();
        this.returnsType = false;
      });
    },
    aReturnGoods() {
      this.$refs.returns.aReturnsClick();
    },
    isTeach(data) {
      this.isNoInstall = data;
    },
    printClick() {
      this.isPrintShow = true;
      setTimeout(() => {
        this.$refs.orderPrint.printPdf();
      }, 1000);
    },
    exportViewClick() {
      this.exportView =
        process.env.VUE_APP_BASE_API +
        "/admin/order/export/" +
        this.form.id +
        "?token=" +
        this.token;
      window.open(this.exportView);
    },
    handleClose(done) {
      this.dialogVisible = false;
    },
    pauseClick() {
      var _this = this;
      const params = new URLSearchParams();
      params.append(
        "beginDate",
        this.pauseDate.length > 0 ? this.pauseDate[0] : ""
      );
      params.append(
        "endDate",
        this.pauseDate.length > 0 ? this.pauseDate[1] : ""
      );
      params.append("orderId", this.form.id);
      pause(params)
        .then((res) => {
          console.log(res);
          _this.$message({
            message: "报停成功",
            offset: 120,
            center: true,
          });
          this.dialogVisible = false;
          _this.findClick();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //  修改地址
    addressClose() {
      var _this = this;
      _this.addressType = false;
      this.receiverId = "";
    },
    addressClick() {
      var _this = this;
      _this.loadReceiver();
      _this.addressType = true;
    },
    chooseClick() {
      var _this = this;
      if (_this.receiverId == "") {
        _this.$message({
          message: "请选择地址",
          offset: 120,
          center: true,
        });
        return;
      }
      const params = new URLSearchParams();
      params.append("orderId", _this.form.id);
      params.append("receiverId", _this.receiverId);
      updateWeekAndReceiver(params)
        .then((res) => {
          console.log(res);
          _this.$message({
            message: "修改成功",
            offset: 120,
            center: true,
          });
          _this.addressType = false;
          _this.receiverId = "";
          _this.findClick();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    loadReceiver() {
      var _this = this;
      const params = new URLSearchParams();
      params.append("memberId", _this.form.memberId);
      addressList(params)
        .then((res) => {
          console.log(res);
          _this.tableData = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentRow = val;
      this.receiverId = val.id;
    },
    //  新增地址
    addressAdd() {
      var _this = this;
      _this.receiverVisible = true;
    },
    receiverClose() {
      this.receiverVisible = false;
    },
    orderReceiver(data) {
      var _this = this;
      _this.tableData.push(data.data);
      _this.receiverClose();
    },
    productFindClick(id){
      var _this = this
      productFind(id).then(res=>{
        _this.detailedList = res.data.article.productMeta.props
      })
    },
    askforConfirmClick(){
      this.$confirm('同意退款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        askforConfirm(this.form.askfor.id).then(response=>{
          this.findClick()
          // EventBus.$emit('order-edit', response.data)
        })
      })
    },
    cancelAskfor(){
      this.$confirm('拒绝退款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        askforCancel(this.form.askfor.id).then(response=>{
          this.findClick()
          // EventBus.$emit('order-edit', response.data)
        })
      })
    },
    refundsAskfor(){
      this.$confirm('确认退款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        askforRefunds(this.form.askfor.id).then(response=>{
          this.findClick()
          // EventBus.$emit('order-edit', response.data)
        })
      })

    },
  },
};
</script>

<style scoped>
.box-card {
  width: 100%;
  box-sizing: border-box;
}

.details_Header {
  display: flex;
  align-items: center;
}

.deleted_Line {
  width: 2px;
  height: 12px;
  background-color: #409eff;
}
.submit_payMethod_Content_Date {
  font-size: 12px;
  font-weight: 400;
  color: rgba(26, 26, 30, 0.3);
  line-height: 36px;
  /* display: block; */
  /* margin-top: 10rpx; */
}
.details_HeaderTitle {
  font-weight: 600;
  margin-left: 5px;
  display: block;
  width: 100px;
}

.deleted_OrderHeader {
  padding-top: 5px;
  padding-bottom: 10px;
  margin: 10px 0;
  border-left: 1px solid #f2f2f2;
  border-bottom: 1px solid #f2f2f2;
}

.deleted_OrderTitle {
}

.deleted_OrderContent {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.details_PayHeader {
  display: flex;
  align-items: center;
  margin-top: 40px;
}

.details_Buyers {
  display: flex;
  align-items: center;
}

.deleted_Row_Headings {
  color: #666666;
}

.deleted_Row_leftTitle{
  width:80px;
  text-align:right;
}

.deleted_OrderName {
  color: #409eff;
  margin-left: 5px;
  width: 250px;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product_header_name {
  width: 100%;
  display: flex;
  align-items: center;
  background-color: #f2f2f2;
  margin-top: 20px;
  font-weight: 600;
}

.el-dialog-div {
  max-height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;
}

.product_header_Plans {
  width: 100%;
  display: flex;
  align-items: center;
  background-color: #f2f2f2;
  margin-top: 20px;
  font-weight: 600;
  justify-content: space-between;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-right: 10px;
  box-sizing: border-box;
}

.product_header_Plans_left {
  display: flex;
  align-items: center;
}
</style>
